package com.game.monitor;

import net.SocketEnum;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;

import com.component.Util;
import com.component.code.TishiManager;
import com.data.spring.BeanFactory;
import com.dictionary.DictionaryTabel;
import com.game.serivce.ConfigService;
import com.game.serivce.DeskPlayerService;
import com.game.serivce.GameRoomService;
import com.game.serivce.RoomDeskService;


public class DataMonitoredService {
	private static Logger logger = Logger.getLogger(DataMonitoredService.class);
	//ttt为换行符
	String diankongShuoming = "无点控 返分池满  黑杰克";//>>>需要改
	boolean[] configIsResetAndroidCount = { false,true,false};//>>>需要改
	
	String[] deskState = {"休眠状态", "等待玩家", "开始游戏","正在下注", "等待发牌", "系统发牌", "等待开奖", "系统开奖", "等待结算", "游戏结算", "结算结束"};
	String[] playerState = { "等待开始", "等待下注","下注状态", "等待开奖", "正在开奖", "等待结算", "正在结算", "玩家离开"};
	String[] configListStr = {"公共参数", "时间参数", "机器人参数", "额外参数"};
	String[] configGetMethod = { "getPublicParams", "getTimeParams", "getAndroidParams", "getExtraParams"};
	String[] configSetMethod = { "setPublicParams", "setTimeParams", "setAndroidParams", "setExtraParams"};
	
	
	String playerModelShuoming ="有红色框为真实玩家ttt有黄色点的为有点控tttttt"
			+ "第一行:玩家IDttt"
			+ "第二行:玩家昵称ttt"
			+ "第三行:下注金币ttt"
			+ "第四行:玩家状态ttt";
	
	public GameRoomService[] gameRoomServices;

	public DataMonitoredService(GameRoomService[] gameRoomService){
		this.gameRoomServices = gameRoomService;
	}

	/***
	 * 连接
	 * @param session
	 */
	public void dataMonitored_CONN(IoSession session){
		try {

			session.setAttribute("joinType", DictionaryTabel.jionStype_jiankongJion);
			
			JSONArray jsonList = new JSONArray();
			for (int i = 0; i < configListStr.length; i++)
			{
				JSONObject json = new JSONObject();
				json.put("configNumber", i);
				json.put("configName", configListStr[i]);
				jsonList.add(json);
			}
			
			JSONObject conn_json = new JSONObject();
			
			conn_json.put("configList", jsonList);
			conn_json.put("diankongShuoming", diankongShuoming);
			conn_json.put("playerModelShuoming", playerModelShuoming);
			
			session.write(SocketEnum.DataMonitored_connI + "@"+conn_json.toString()+"@&");
		} catch (Exception e) {
			
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}
	
	/***
	 * 房间列表
	 * @param session
	 */
	public void dataMonitored_ROOMLIST(IoSession session){
		try {
			JSONArray jsonList = new JSONArray();
			for (int i = 0; i < gameRoomServices.length; i++) {
				if (gameRoomServices[i] == null) 
					continue;
				
				JSONObject json = new JSONObject();
				json.put("roomId", i);
				json.put("roomName", gameRoomServices[i].configRoomService.roomName);
				
				if(gameRoomServices[i].androidManage == null)
					json.put("androidCount","无机器人");
				else
					json.put("androidCount", gameRoomServices[i].androidManage.androidServices_Useing.size() 
							+ " | " 
							/*+ gameRoomServices[i].androidManage.androidServices_Available.size()
							+ " | " */
							+ gameRoomServices[i].androidManage.androidServices.size());
				
				
				json.put("onlineCount", gameRoomServices[i].getOnlineCount());
				json.put("waitCount", gameRoomServices[i].waitJoinPlayers.size());
				json.put("playerCount", gameRoomServices[i].configRoomService.oneDeskhavePlayerCount);
				
				jsonList.add(json);
			}

			session.write(SocketEnum.DataMonitored_getRoomListI + "@" + jsonList.toString() + "@&");
		}
		catch(Exception e)
		{
			logger.error(e.getMessage(), e);
		}
	}
	
	/***
	 * 桌子列表
	 * @param session
	 * @param str
	 */
	public void dataMonitored_GETDESKLIST(IoSession session, String str) {
		try {
			int index = Integer.valueOf(str);
			JSONArray jsonList = new JSONArray();
			JSONArray jsonList_player;
			
			RoomDeskService roomDeskService;
			DeskPlayerService[] deskPlayerServices;
			
			for (int i = 0; i < gameRoomServices[index].roomDeskServices.length; i++) {
				roomDeskService = gameRoomServices[index].roomDeskServices[i];
				
				if (roomDeskService == null)
					continue;
				
				JSONObject json = new JSONObject();
				json.put("deskId", roomDeskService.configDesk.getDeskNum());
				json.put("onLine", roomDeskService.getRealPlayersCount() + " | " + roomDeskService.getPlayersCount());
				int state = roomDeskService.configDesk.getGameState();
				
				if (state == -1) 
					json.put("stateMiaosu", "关闭状态");
				else 
					json.put("stateMiaosu", deskState[state]);
					
				deskPlayerServices = roomDeskService.deskPlayerServices;
				jsonList_player = new JSONArray();
				DeskPlayerService deskPlayerService;
				for(int j = 0; j < deskPlayerServices.length; j++){
					deskPlayerService = deskPlayerServices[j];
					JSONObject json_player = new JSONObject();
					if (deskPlayerService == null)
						json_player.put("isHavePlayer", 0);
					else
					{
						json_player.put("isHavePlayer", 1);
						json_player.put("playerId", deskPlayerService.getPlayerService().deskPlayer.getPlayerId());
						json_player.put("playerDiankong", "0");
						json_player.put("playerType", deskPlayerService.getPlayerService().deskPlayer.getPlayerType());
						//下面三个参数自由设置想看的
						json_player.put("playerMiaoshu1", deskPlayerService.getPlayerService().deskPlayer.getNickName());
						json_player.put("playerMiaoshu2", deskPlayerService.getPlayerService().deskPlayer.getTotalMoney());
						json_player.put("playerMiaoshu3",  playerState[deskPlayerService.getPlayerService().deskPlayer.getState()]);
					}
					
					jsonList_player.add(json_player);
				}
				
				json.put("players", jsonList_player);
				jsonList.add(json);
			}

			session.write(SocketEnum.DataMonitored_getDeskListI + "@" + jsonList.toString() + "@&");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	/***
	 * 得到桌子信息
	 * @param session
	 * @param str
	 */
	public void dataMonitored_GETDESKINFO(IoSession session, String str){
		try {/*
			String[] arr = str.split(",");
			int roomId = Integer.valueOf(arr[0]);
			int deskId = Integer.valueOf(arr[1]);
			RoomDeskService roomDeskService = gameRoomServices[roomId].roomDeskServices[deskId];
			
			JSONObject json = new JSONObject();
			// =========================== ttt 替换为\n
			StringBuffer deskInfo = new StringBuffer();
			if (roomDeskService.configDesk.getGameState() == -1)
				deskInfo.append("关闭状态");
			else 
				deskInfo.append(deskState[roomDeskService.configDesk.getGameState()]);

			deskInfo.append("【").append(roomDeskService.lastGameTime).append("秒】ttt");
			deskInfo.append("奖金池：").append(gameRoomServices[roomId].configRoom.getJackpot()).append("ttt");
			if (roomDeskService.configDesk.getSpList().size() > 0) {
				deskInfo.append("庄手牌：").append(roomDeskService.configDesk.getSpList()).append("ttt");
				deskInfo.append("庄点数：").append(BlackJackRule.getRealDianShu(BlackJackRule.getSpDianShu(roomDeskService.configDesk.getSpList()))).append("ttt");
			}
			deskInfo.append("ttt");
			deskInfo.append("剩余牌：ttt");
			deskInfo.append(roomDeskService.configDesk.getCards());
			List<String> list = new ArrayList<String>();
			list.addAll(roomDeskService.gameRecord);
			Iterator<String> ite = list.iterator();
			while(ite.hasNext()){
				deskInfo = deskInfo + ite.next().replace("@&", ")ttt").replace("@", "-->(");
			}

			// ===========================
			StringBuffer playerInfo = new StringBuffer();
			DeskPlayerService deskPlayerservice;
			for (int i = 0; i < roomDeskService.deskPlayerServices.length; i++) {
				deskPlayerservice = roomDeskService.deskPlayerServices[i];
				if (deskPlayerservice != null && deskPlayerservice.deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_People) {
					playerInfo.append(i + "：").append(deskPlayerservice.deskPlayer.getPlayerId() + "("+ deskPlayerservice.deskPlayer.getNickName() + ")<" + playerState[deskPlayerservice.deskPlayer.getState()] + ">");
					playerInfo.append("ttt      下注金额：" + BlackJackRule.getBetMoney(deskPlayerservice.deskPlayer.getBetInfo(), roomDeskService.gameRoomeService.configRoom.chipMultiple));
					for (ArrayList<Integer> spList : deskPlayerservice.deskPlayer.getSpList()) {
						playerInfo.append("ttt      当前手牌：" + spList).append("<" + BlackJackRule.getRealDianShu(BlackJackRule.getSpDianShu(spList)) + ">");
					}
					playerInfo.append("tttttt");
				}
			}
			json.put("deskInfo_desk", deskInfo.toString());
			json.put("deskInfo_player", playerInfo.toString());
			// ===========================
			session.write(SocketEnum.DataMonitored_getDeskInfoI + "@" + json.toString() + "@&");
		*/} catch (Exception e) {
			logger.error(e.getMessage(), e);

		}
	}
	/***
	 * 单个玩家信息
	 * @param session
	 * @param str
	 */
	public void dataMonitored_GETPLAYERINFO(IoSession session, String str){
		try {
			String[] arr = str.split(",");
			int roomId = Integer.valueOf(arr[0]);
			int deskId =Integer.valueOf(arr[1]);
			int seatId = Integer.valueOf(arr[2]);
		
			String mess = "基础数据ttt";
			RoomDeskService roomDeskService = gameRoomServices[roomId].roomDeskServices[deskId];

			DeskPlayerService deskPlayerservice = roomDeskService.deskPlayerServices[seatId];

			if (deskPlayerservice == null)
				return;
			
			mess = mess + "    会员等级：" + deskPlayerservice.getPlayerService().deskPlayer.getVipLevel() + "ttt";
			mess = mess + "ttttttttt";
			mess = mess + "    背包数据ttt";
			mess = mess + deskPlayerservice.getPlayerService().deskPlayer.getBagInfo().toString();
			mess = mess + "ttttttttt";
			mess = mess + "游戏数据ttt";		
			mess = mess + "    下注金额：" + deskPlayerservice.getPlayerService().deskPlayer.getTotalMoney() + "ttt";
			mess = mess + "    下注明细：" + deskPlayerservice.getPlayerService().deskPlayer.getBetInfo() + "ttt";

			mess = mess + "ttttttttt";
			mess = mess + "点控数据ttt";
			mess = mess + "    无ttt";
			mess = mess + "ttttttttt";
			
			session.write(SocketEnum.DataMonitored_getPlayerInfoI + "@" + mess + "@&");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	/***
	 * 发广播
	 * @param session
	 * @param str
	 */
	public void dataMonitored_SENDGUANGBO(IoSession session, String str){
		try {
			String[] ss = str.split("\\*");
			int roomId = Integer.valueOf(ss[0]);
			if (roomId == -1) {
				for (int i = 0; i < gameRoomServices.length; i++) {
					gameRoomServices[i].guangboService.addGuangboStr(ss[1]);
				}
			} else {
				gameRoomServices[roomId].guangboService.addGuangboStr(ss[1]);
			}
			session.write("0@" + TishiManager.Tishi_Send_Success + "@&");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	/***
	 * 配置列表
	 * @param session
	 * @param str
	 */
	public void dataMonitored_GETCONFIG(IoSession session, String str){
		try {
			String[] strs = str.split(",");
			int configId =  Integer.valueOf(strs[0]);
			int roomId = Integer.valueOf(strs[1]);
			//字段ID;字段名次;是否开启修改;默认值[*字段ID;字段名次;是否开启修改;默认值]
			session.write(SocketEnum.DataMonitored_getConfigI + "@" + configId + "#" + Util.doMethod(ConfigService.getInstance(), configGetMethod[configId], roomId) + "@&");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	/***
	 * 重读数据库
	 * @param session
	 */
	public void dataMonitored_READDB(IoSession session) {
		try {
			ConfigService.getInstance().readAllConfig();;
			session.write("0@" + TishiManager.Tishi_Read_Success + "@&");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	/***
	 * 等待列表
	 * @param session
	 * @param str
	 */
	public void dataMonitored_GETWAITINFO(IoSession session, String str){
		try {
			int index = Integer.valueOf(str);
			JSONArray jsonList_player = new JSONArray();
			DeskPlayerService waitPlayerService;
			for (int i = 0; i < gameRoomServices[index].waitJoinPlayers.size(); i++) {
				waitPlayerService = gameRoomServices[index].waitJoinPlayers.get(i);
				JSONObject json = new JSONObject();	

				json.put("info", waitPlayerService.getPlayerService().deskPlayer.getPlayerId() + "(" + waitPlayerService.getPlayerService().deskPlayer.getNickName() + ")");
				jsonList_player.add(json);
			}
			
			JSONArray jsonList_desk = new JSONArray();
			RoomDeskService roomDeskService;
//			for (int i = 0; i < gameRoomServices[index].haveWaitPlayerDeskServices.size(); i++) {
//				roomDeskService = gameRoomServices[index].haveWaitPlayerDeskServices.get(i);
//
//				JSONObject json = new JSONObject();
//				json.put("info", "桌号：" + roomDeskService.configDesk.getDeskNum() + "    在线：" + roomDeskService.getRealPlayersCount() + " | " + roomDeskService.getPlayersCount() + " | "
//						+ roomDeskService.gameRoomeService.configRoomService.oneDeskhavePlayerCount);
//				jsonList_desk.add(json);
//			}
			

			JSONObject json = new JSONObject();
			json.put("playerList", jsonList_player);
			json.put("deskList", jsonList_desk);
			session.write(SocketEnum.DataMonitored_getWaitInfoI + "@" + json.toString() + "@&");
		
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	/***
	 * 关闭桌子
	 * @param session
	 * @param str
	 */
	public void dataMonitored_CLOSEDESK(IoSession session, String str){
		try {
			String[] arr = str.split(":");
			boolean isNow = false;
			if (arr[0].equals("1")) {
				isNow = true;
			}
			int roomId = Integer.valueOf(arr[1]);
			
			if (arr[3].equals("-1")){
				for(int i = 0 ; i < gameRoomServices[roomId].roomDeskServices.length; i ++){
					//if (gameRoomServices[roomId].roomDeskServices[i] != null)
						//gameRoomServices[roomId].roomDeskServices[i].closeDesk(arr[2], isNow);
				}
			}
			else {
				for(String deskNum : arr[3].split(",")){
					//gameRoomServices[roomId].roomDeskServices[Integer.parseInt(deskNum)].closeDesk(arr[2], isNow);
				}
			}

			session.write("0@" + TishiManager.Tishi_Close_Success + "@&");

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			session.write("0@" + TishiManager.Tishi_Close_Fail + "@&");
		}
	}
	/***
	 * 启动桌子
	 * @param session
	 * @param str
	 */
	public void dataMonitored_STARTDESK(IoSession session, String str){
		try {
			String[] arr = str.split(":");
			boolean isNow = false;
			if (arr[0].equals("1")) {
				isNow = true;
			}

			int roomId = Integer.valueOf(arr[1]);
			if (arr[3].equals("-1")){
				for(int i = 0 ; i < gameRoomServices[roomId].roomDeskServices.length; i ++){
					//if (gameRoomServices[roomId].roomDeskServices[i] != null)
						//gameRoomServices[roomId].roomDeskServices[i].startDesk(arr[2], isNow);
				}
			}
			else {
				for(String deskNum : arr[3].split(",")){
					//gameRoomServices[roomId].roomDeskServices[Integer.parseInt(deskNum)].startDesk(arr[2], isNow);
				}
			}
			
			session.write("0@" + TishiManager.Tishi_Close_Success + "@&");

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			session.write("0@" + TishiManager.Tishi_Close_Fail + "@&");
		}
	}
	/***
	 * 更新配置
	 * @param session
	 * @param str
	 */
	public void DataMonitored_UPDATACONFIG(IoSession session, String str){
		try {
			String[] strs = str.split(">");

			int configNumber = Integer.valueOf(strs[0]);
			int isChangeAll = Integer.valueOf(strs[1]);
			int nowRoomId = Integer.valueOf(strs[2]);
			String roomIdStr =  strs[3];
			
			if (isChangeAll == 2) {
				for (int i = 0; i < ConfigService.getInstance().configRooms.size(); i++) {
					
					if (!roomIdStr.contains("," + i + ","))
						continue;
					
					boolean f = changeConfig(session, i, strs[4]);
					
					Util.doMethod(ConfigService.getInstance(),configSetMethod[configNumber], i);
					if (i == nowRoomId && f) 
						session.write(SocketEnum.DataMonitored_getConfigI + "@"+configNumber + "#" + Util.doMethod(ConfigService.getInstance(), configGetMethod[configNumber], nowRoomId) + "@&");
					
					if (f && configIsResetAndroidCount[configNumber]) 
						gameRoomServices[nowRoomId].androidManage.setAndroidCount();
				}
			} 
			else if (isChangeAll == 1) {
				for (int i = 0; i < ConfigService.getInstance().configRooms.size(); i++) {
					boolean f = changeConfig(session, i, strs[4]);
					
					Util.doMethod(ConfigService.getInstance(),configSetMethod[configNumber], i);
					if (i == nowRoomId && f) {
						session.write(SocketEnum.DataMonitored_getConfigI + "@"+configNumber + "#" + Util.doMethod(ConfigService.getInstance(), configGetMethod[configNumber], nowRoomId) + "@&");
					}
					
					if (f&&configIsResetAndroidCount[configNumber]) {
						gameRoomServices[nowRoomId].androidManage.setAndroidCount();
					}
				}
			} else {
				boolean f = changeConfig(session, nowRoomId, strs[4]);
				Util.doMethod(ConfigService.getInstance(),configSetMethod[configNumber], nowRoomId);
				if (f) {
					session.write(SocketEnum.DataMonitored_getConfigI + "@"+configNumber + "#" + Util.doMethod(ConfigService.getInstance(), configGetMethod[configNumber], nowRoomId) + "@&");
					
					if (configIsResetAndroidCount[configNumber]) 
						gameRoomServices[nowRoomId].androidManage.setAndroidCount();
				}
			}

			session.write("0@" + TishiManager.Tishi_Modity_Success + "@&");
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	
	private boolean changeConfig(IoSession session, int roomId, String str) {
		String[] datas = str.split(";");
		com.data.model.ConfigRoom configRoom = ConfigService.getInstance().configRooms.get(roomId);
		try {
			for (int i = 0; i < datas.length; i++) {
				if (datas[i].length() <= 0) 
					continue;
				
				String[] strs = datas[i].split("\\^");
				String propName = strs[0];
				String propValue = strs[1];
				Util.setMethod(configRoom, propName, propValue);
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			session.write("0@" + TishiManager.Tishi_Modity_Fail + "@&");
			return false;
		}
		try {
			ConfigService.getInstance().updateConfigRoomForDB(configRoom);
			session.write("0@" + TishiManager.Tishi_Modity_Success + "@&");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			session.write("0@" + TishiManager.Tishi_Modity_Fail + "@&");
			return false;
		}
		return true;
	}

	/***
	 * 点控列表
	 * @param session
	 * @param str
	 *//*
	public void dataMonitored_GETPOINTCONTROLLIST(IoSession session, String str) {

		long playerId = Long.valueOf(str);

		try {

			session.write(SocketEnum.DataMonitored_getPointControlListI + "@" + JSONArray.fromObject(Util.PlayerService.getAllDianKongInfo(playerId)).toString() + "@&");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	*//***
	 * 添加点控
	 * @param session
	 * @param str
	 *//*
	public void dataMonitored_ADDPOINTCONTROL(IoSession session, String str) {
		try {
			String[] arr = str.split(",");

			int roomId = Integer.valueOf(arr[0]);
			String deskId = arr[1];
			int posId = Integer.valueOf(arr[2]);
			long playerId = Long.valueOf(arr[3]);
			long tagerFenshu = Long.valueOf(arr[4]);
			float rate = Float.valueOf(arr[5]);

			PlayerDiankong playerDiankong = new PlayerDiankong();
			playerDiankong.setPlayerId(playerId);
			playerDiankong.setTargetFen(tagerFenshu);
			playerDiankong.setDianKongRate(rate);
			playerDiankong.setCreateTime(new Timestamp(System.currentTimeMillis()));
			playerDiankong.setIsFinish(0);
			playerDiankong.setFinishFen((long)0);

			Util.PlayerService.updateDianKongInfo(playerDiankong);

			dataMonitored_GETPOINTCONTROLLIST(session, playerId + "");

			if (roomId >= 0 && deskId.length()>0) {
				PlayerDeskService playerService = roomServices[roomId].deskMap.get(deskId).playerDeskServices[posId];
				if (playerService == null) {
					return;
				}
				if (playerService.getBasePlayer().getPlayerID().endsWith(playerId + "") 
						&& playerService.getPlayer().getPlayerDiankong() == null) {
					playerService.getdiankong(playerId + "");
				}
			}
			session.write(SocketEnum.infoI + "@"
					+ TishiManager.Tishi_Modity_Success + "@&");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}

	}

	*//***
	 * 删除点控
	 * @param session
	 * @param str
	 *//*
	public void dataMonitored_DELPOINTCONTROL(IoSession session, String str) {
		try {
			String[] arr = str.split(",");
		
			int roomId = Integer.valueOf(arr[0]);
			String deskId = arr[1];
			int posId = Integer.valueOf(arr[2]);
			long playerId = Long.valueOf(arr[3]);
			long diankongId = Long.valueOf(arr[4]);

			Util.PlayerService.deleteDianKongInfoById(diankongId);
			
			dataMonitored_GETPOINTCONTROLLIST(session, playerId + "");
			if (roomId >= 0 && deskId.length() > 0) {
				PlayerDeskService playerService = roomServices[roomId].deskMap.get(deskId).playerDeskServices[posId];
				if (playerService.getBasePlayer().getPlayerID().endsWith(playerId + "") && playerService.getPlayer().getPlayerDiankong() != null
						&& playerService.getPlayer().getPlayerDiankong().getId() == diankongId) {

					roomServices[roomId].deskMap.get(deskId).finishDiankong(playerService, playerService.getPlayer().getPlayerDiankong());

				}
			}
			session.write(SocketEnum.infoI + "@"
					+ TishiManager.Tishi_Modity_Success + "@&");

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}

	}*/
}
